package com.gmrz.uap.common;

import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.naming.*;
import java.util.Enumeration;
import java.util.Hashtable;

public class UAPDataSourceFactory extends BasicDataSourceFactory {
    private static final Logger LOG = LogManager.getLogger(UAPDataSourceFactory.class);
    private static final String KEY_PASSWORD = "password";
    byte[] LMK_CODE = new byte[]{-83, -58, 125, -124, 115, -65, 47, 6, -83, -58, 125, -124, 115, -65, 47, 6};

    public static final String ALIGORITHM_SM4_ECB = "SM4_ECB";

    public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) {
        try {
            if ((obj instanceof Reference)) {
                decryptAndReplacePassword((Reference) obj);
            }
            return super.getObjectInstance(obj, name, nameCtx, environment);
        } catch (Exception ex) {
            LOG.error("Unexpected error while trying to get connection using datasource.", ex);
            //throw new UAFRuntimeException("Unexpected error while trying to get connection using datasource.", ex);
        }
        return null;
    }

    private void decryptAndReplacePassword(Reference ref) {
        Enumeration refAddr = ref.getAll();
        int idx = 0;
        String passwd = null;
        while (refAddr.hasMoreElements()) {
            RefAddr ad = (RefAddr) refAddr.nextElement();
            if (ad.getType().equals(KEY_PASSWORD)) {
                break;
            }
            idx++;
        }
        if (null != ref.get("password")) {
            passwd = (String) ref.get("password").getContent();
        }
        /*if (passwd != null) {
            try {
                SymDecryptOperator sm4DECBPKS5 = new SymDecryptOperator(EncryptContants.getEncryptInfoAlg(), EncryptContants.getEncryptKeyPading(), LMK_CODE, EncryptContants.getEncryptKeyIV());
                byte[] encryptKey = sm4DECBPKS5.Boc_Decrypt(ByteUtils.hex2byte(passwd));
                passwd = new String(encryptKey);
            } catch (Exception ex) {
                LOG.error("Failed to decrypt the database password provided in resource configuration.", ex);
                throw new UAFRuntimeException("Failed to decrypt the database password provided in resource configuration.", ex);
            }
            ref.remove(idx);
            ref.add(idx, new StringRefAddr("password", passwd));
        } else {
            LOG.error("Password is null ");
        }*/
    }
}
